import { createRouter, createWebHistory } from 'vue-router'
import HomePage from '../views/Home.vue'
import LoginPage from '../views/Login.vue'
import RegisterPage from '../views/Register.vue'
import MerchantDashboard from '../views/MerchantDashboard.vue'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: HomePage
  },
  {
    path: '/login',
    name: 'Login',
    component: LoginPage
  },
  {
    path: '/register',
    name: 'Register',
    component: RegisterPage
  },
  {
    path: '/services',
    name: 'Services',
    component: () => import('../views/Services.vue')
  },
  {
    path: '/services/:id',
    name: 'ServiceDetail',
    component: () => import('../views/ServiceDetail.vue')
  },
  {
    path: '/appointment/:id',
    name: 'Appointment',
    component: () => import('../views/Appointment.vue')
  },
  {
    path: '/payment/:id',
    name: 'Payment',
    component: () => import('../views/Payment.vue')
  },
  {
    path: '/payment/success',
    name: 'PaymentSuccess',
    component: () => import('../views/PaymentSuccess.vue')
  },
  {
    path: '/orders',
    name: 'Orders',
    component: () => import('../views/Orders.vue')
  },
  {
    path: '/orders/:id',
    name: 'OrderDetail',
    component: () => import('../views/OrderDetail.vue')
  },
  {
    path: '/profile',
    name: 'Profile',
    component: () => import('../views/Profile.vue')
  },
  {
    path: '/review/:id',
    name: 'Review',
    component: () => import('../views/Review.vue')
  },
  {
    path: '/admin',
    name: 'Admin',
    component: () => import('../views/Admin.vue')
  },
  {
    path: '/merchant',
    name: 'MerchantDashboard',
    component: MerchantDashboard,
    meta: {
      requiresAuth: true,
      requiresMerchant: true
    }
  },
  {
  path: '/merchant/dashboard',
  component: () => import('@/views/MerchantDashboard.vue'),
  meta: { requiresAuth: true, requiresMerchant: true }
}
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

router.beforeEach((to, from, next) => {
  const currentUser = JSON.parse(localStorage.getItem('currentUser'));
  const isMerchant = currentUser && currentUser.userType === 'merchant';

  if (to.meta.requiresAuth && !currentUser) {
    next('/login'); // 未登录跳转到登录页面
  } else if (to.path === '/merchant/dashboard' && !isMerchant) {
    next('/'); // 非商家用户尝试访问商家管理页面，跳转到首页
  } else {
    next(); // 正常访问
  }
});

export default router 